<?php

namespace app\api\controller\xilujob;

use app\common\controller\xilujob\XilujobApi;
use app\common\model\xilujob\CompanyProfile;
use app\common\model\xilujob\JobInterview AS JobInterviewModel;
use app\common\model\xilujob\XilujobUser;
use think\Exception;

class JobInterview extends XilujobApi {

    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];
    protected $restrictedActions = ['*'];

    /**
     * @ApiTitle (个人查看面试Tab数量)
     * @ApiSummary (邀请面试列表)
     * @ApiMethod (POST)
     * @ApiRoute (/api/xilujob.job_interview/personal_list_count)
     */
    public function personal_list_count() {

//        if($status != -1){
//            $where['job_interview.status'] = $status;
//        }else{
//            $where['job_interview.status'] = ['in',[1,5]];
//        }
        $data = ['tab_0'=>0,'tab_1'=>0,'tab_2'=>0,'tab_3'=>0,'tab_4'=>0];
        $interviews = JobInterviewModel::alias("job_interview")
            ->field('job_interview.status,count(*) num')
            ->join("XilujobJob job","job.id=job_interview.job_id")
            ->join("XilujobEnterpriseInfo enterpriseinfo","enterpriseinfo.company_id=job_interview.company_id")
            ->where('job_interview.user_id', $this->auth->id)
            ->group('job_interview.status')
            ->select();

        foreach ($interviews as $interview) {
           $data['tab_'.$interview['status']] = $interview['num'];
        }
        $this->success('查询成功', $data);
    }

    /**
     * @ApiTitle (个人查看面试列表)
     * @ApiSummary (邀请面试列表)
     * @ApiMethod (POST)
     * @ApiRoute (/api/xilujob.job_interview/personal_list)
     */
    public function personal_list() {
        $page = abs($this->request->param('page'));
        $status = $this->request->param('status',0);
        $page = $page>0 ? $page : 1;
        $pagesize = abs($this->request->param('pagesize',10));
        if($status != -1){
            $where['job_interview.status'] = $status;
        }else{
            $where['job_interview.status'] = ['in',[1,5]];
        }
        $interviews = JobInterviewModel::with([
                'job'=>function($query){$query->withField('id,job_name,city_id,town_id,publisher_id,salary_type,salary_min,salary_max');},
                'enterpriseinfo'=>function($query){$query->withField('id,full_name,company_name,logo');},
            ])
            ->where('job_interview.user_id', $this->auth->id)
            ->where($where)
//            ->order('interview_time','asc')
            ->order('job_interview.id','desc')
            ->limit(($page-1)*$pagesize, $pagesize)
            ->select();
        foreach ($interviews as $interview) {
            //fixme: tp5无法正常使用with嵌套预加载， 只能在循环中读取
            $interview->job->relationQuery(['city'=>function($query){$query->withField('id,shortname,name');}]);
        }
        unset($interview);
        $this->success('查询成功', $interviews);
    }


    /**
     * @ApiTitle (个人改变面试状态)
     * @ApiSummary (个人改变面试状态)
     * @ApiMethod (POST)
     * @ApiRoute (/api/xilujob.job_interview/multi_status)
     * @ApiHeaders (name=token, type=string, require=true, description="Token")
     * @ApiParams (name=interview_id, type=int, require=true, description="邀请面试id")
     * @ApiParams (name=status, type=int, require=true, description="修改状态")
     */
    public function multi_status() {
        $job_interview_id = $this->request->param('interview_id',0);
        $jobInterview = JobInterviewModel::get($job_interview_id);
        if(!$jobInterview) {
            $this->error(__('no record'));
        }
        $status = $this->request->post('status');
        $job = \app\common\model\xilujob\Job::get($jobInterview->job_id);
        if(!$job){
            $this->error("职位不存在或已下架");
        }
        if(in_array($status, [JobInterviewModel::STATUS_INTERVIEW_REJECTED,JobInterviewModel::STATUS_INTERVIEW_ACCEPTED])
            && $this->auth->id!=$jobInterview->user_id) {
            // 非目标用户
            $this->error(__('no record'));
        }
        else if(in_array($status, [JobInterviewModel::STATUS_INTERVIEW_FAILED,JobInterviewModel::STATUS_INTERVIEW_PASSED])){
            $company = CompanyProfile::get(['user_id'=>$this->auth->id]);
            if(!$company || $company->id != $jobInterview->company_id) {
                // 非目标企业
                $this->error(__('no record'));
            }
        }

        try {
            $ret = $jobInterview::transitStatus($jobInterview, $status);
        }catch (Exception $e){
            $this->error($e->getMessage());
        }

        $this->success('修改成功', $ret);
    }


    public function company_list_count() {
        $company = CompanyProfile::get(['user_id'=>$this->auth->id]);
        $data = ['tab_0'=>0,'tab_1'=>0,'tab_2'=>0,'tab_3'=>0,'tab_4'=>0];
        $interviews = JobInterviewModel::alias("job_interview")
            ->field('job_interview.status,count(*) num')
            ->join("XilujobJob job","job.id=job_interview.job_id")
            ->join("XilujobEnterpriseInfo enterpriseinfo","enterpriseinfo.company_id=job_interview.company_id")
            ->where('job_interview.company_id', $company->id)
            ->group('job_interview.status')
            ->select();

        foreach ($interviews as $interview) {
            $data['tab_'.$interview['status']] = $interview['num'];
        }
        $this->success('查询成功', $data);
    }
    /**
     * 企业查看面试列表
     */
    public function company_list() {
        $status = $this->request->param('status');
        $company = CompanyProfile::get(['user_id'=>$this->auth->id]);
        $interviews = JobInterviewModel::with([
            'resume',
            'job'=>function($query){$query->withField('id,job_name');}
        ])->where('company_id', $company->id);
        if(!in_array($status, [JobInterviewModel::STATUS_INTERVIEW_SENT, JobInterviewModel::STATUS_INTERVIEW_REJECTED])) {
            $interviews->whereIn('job_interview.status',[JobInterviewModel::STATUS_INTERVIEW_ACCEPTED, JobInterviewModel::STATUS_INTERVIEW_FAILED, JobInterviewModel::STATUS_INTERVIEW_PASSED]);
        }else {
            $interviews->where('job_interview.status', $status);
        }
        $interviews->order('updatetime','desc');
//        $page = abs($this->request->param('page'));
//        $page = $page>0 ? $page : 1;
        $pagesize = abs($this->request->param('pagesize',10));
        $interviews = $interviews
            //->limit(($page-1)*$pagesize, $pagesize)
            ->paginate($pagesize);
        foreach($interviews as $interview) {
            //fixme: tp5无法正常使用with嵌套预加载， 只能在循环中读取
            $interview->resume->relationQuery(['personal']);
        }
        $this->success('',$interviews);
    }

    /**
     *企业邀请面试
     */
    public function create_interview() {
        $xiluuser = XilujobUser::get(['user_id'=>$this->auth->id]);
        if($xiluuser->enterprise_model->audit_status!=1) {
            $this->error('企业审核通过后方可邀请面试');
        }
        $params = $this->request->post();
        $params['company_id'] = $xiluuser->enterprise_model->id;
        try {
            $ret = JobInterviewModel::createInterview($params);
        }catch (Exception $e){
            $this->error($e->getMessage());
        }

        $this->success('',['interview'=>$ret]);

    }


}